package org.chameleon.datasource.factory;

import org.chameleon.datasource.manager.LocalConfigManager;
import org.chameleon.lang.ConfigAbleManager;
import org.chameleon.lang.cache.Refreshable;

import java.util.Map;
import java.util.Objects;



/**
 * 抽象动态工厂类
 * @see AbsDynamicCacheFactory#refresh(Map)
 * @param <T>
 * @param <P>
 */
public abstract class AbsDynamicCacheFactory<T,P> extends AbsCacheFactory<T,P> implements Refreshable<Map<String,T>> {

    private ConfigAbleManager<T> manager;


    public AbsDynamicCacheFactory(ConfigAbleManager<T> manager) {
        this.manager = manager;
        manager.addRefreshListener(this);

    }
    public AbsDynamicCacheFactory() {
        manager = new LocalConfigManager();
        manager.addRefreshListener(this);
    }


    public abstract P create(T t);

    /**
     * 获取配置远程配置
     * @param t
     * @return
     */
    public T getDynamicConfig(T t){
        final T config = manager.getConfig(t);
        return Objects.isNull(config)?t:config;
    }

    @Override
    public P createP(T t) {
        final T t1 = manager.loadFromDateSource(t);
        if (Objects.nonNull(t1)){
            return create(t1);
        }
        return create(t);
    }

    @Override
    public void refresh(Map<String,T> map) {
        //分两种情况，一种是工厂更新直接new，一种是商品更新原有的对象上更新
        map.keySet().forEach(key->{
            final T t = map.get(key);
            final P p = get(t);
            if (p instanceof Refreshable ){
                ((Refreshable<T>) p).refresh(t);
            }else {
                put(getCacheKey(t),create(t));
            }
        });
    }
}
